package com.pi.shisan.test.client;

import com.pi.shisan.test.client.encoder.MsgEncoder;
import com.pi.shisan.test.client.receiver.MessageValid;
import com.pi.shisan.test.client.receiver.ReceiverDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.CountDownLatch;

/**
 * @author Shisan
 * @version V1.0.0
 * @Package com.test.server
 * @ClassName: Starter
 * @Description:
 * @date 2019年12月17日 10:54
 */
public class StarterClient {

    public static void main(String[] args) throws Exception{

        new StarterClient().init();
    }
    private Channel channel;
    private void init() throws Exception{
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup parent = new NioEventLoopGroup();
        ChannelFuture bind = bootstrap
                .group(parent)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel c) throws Exception {
                        channel = c;
                        c.pipeline().addLast(new MessageValid())
                                .addLast(new ReceiverDecoder())
                                .addLast(new MsgEncoder());
                    }
//                }).connect("192.168.31.126",9000);
    }).connect("192.168.31.126"/*"127.0.0.1"*/,9000);
        CountDownLatch l = new CountDownLatch(1);
        bind.addListener(future -> {
            if(future.isSuccess()){
                try {
                    channel.write((short)1);
                    channel.writeAndFlush((short)0);
                } catch (Exception e) {
                    l.countDown();
                }
            }else{
                l.countDown();
                System.out.println("连接失败");
                future.cause().printStackTrace();
                parent.shutdownGracefully();
            }
        });
        l.await();
    }
}
